package com.collapse.union.gitee.liteflow.design.demo.config;

import com.yomahub.liteflow.springboot.config.LiteflowMainAutoConfiguration;
import com.yomahub.liteflow.springboot.config.LiteflowPropertyAutoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Map;

@Configuration
@AutoConfigureBefore(value = {LiteflowPropertyAutoConfiguration.class, LiteflowMainAutoConfiguration.class})
public class DataSourceInitializer {
    private static final Logger log = LoggerFactory.getLogger(DataSourceInitializer.class);

    @Autowired
    private DataSource dataSource;

    @Value("classpath:sql/ddl.sql")
    private Resource ddl;

    @Value("classpath:sql/dml.sql")
    private Resource dml;

    @PostConstruct
    public void startDbInitializer() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        try {
            Map map = jdbcTemplate.queryForMap("select count(1) from chain_info");
        } catch (Exception e) {
            // 报错,表不存在,初次导入，执行相关脚本
            initSql(ddl);
            initSql(dml);
        }
    }

    private void initSql(Resource resource) {
        log.info("---------->初始化脚本，开始执行-->:" + resource.getFilename());
        try {
            Connection conn = DataSourceUtils.getConnection(dataSource);
            EncodedResource er = new EncodedResource(resource, "utf-8");
            ScriptUtils.executeSqlScript(conn, er);
            log.warn("---------->初始化脚本，执行完成-->:" + resource.getFilename());
        } catch (Exception e) {
            log.warn("---------->初始化脚本，执行失败-->:", e);
        }
    }
}
